package commons.base.luncene;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.queryparser.classic.ParseException;

import commons.base.util.BeanUtil;

public abstract class BaseIndexService {

	private static final Logger log = LogManager.getLogger(BaseIndexService.class);
	
	protected IndexDir indexDir;
	
	public BaseIndexService(String indexPath) throws IOException{
		indexDir = new IndexDir(indexPath);
	}
	
	/**
	 * 修改写入磁盘
	 * @return
	 * @throws IOException
	 */
	public BaseIndexService commit() throws IOException{
		indexDir.getUpdater().commit();
		return this;
	}
	
	public BaseIndexService flush() throws IOException{
		indexDir.getUpdater().flush();
		return this;
	}
	
	public BaseIndexService clear() throws IOException{
		indexDir.getUpdater().deleteAll();
		indexDir.getUpdater().commit();
		return this;
	}
	
	public void close(){
		if(indexDir != null){
			indexDir.close();
		}
	}
	
	public <T> List<T> search(String field, String value, Class<T> clazz) throws IOException, ParseException{
		List<Map<String, String>> mapList = search(field, value);
		List<T> list = new ArrayList<T>();
		
		try {
			for(Map<String, String> map : mapList){
				list.add(BeanUtil.fill(clazz, map));
			}
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
		}
		
		return list;
	}
	
	public List<Map<String, String>> search(String field, String value) throws IOException, ParseException{
		List<Document> docList = indexDir.search(field, value, 1000);
		
		List<Map<String, String>> results = new ArrayList<Map<String, String>>(); 
		
		for(Document doc : docList){
			Map<String, String> row = new HashMap<String, String>();
			
			for(IndexableField f : doc.getFields()){
				row.put(f.name(), f.stringValue());
			}
			
			results.add(row);
		}
		
		return results;
	}
	
}
